<?php

namespace addons\shopro\controller\goods;

use addons\shopro\controller\Common;
use addons\shopro\service\goods\GoodsService;
use app\admin\model\shopro\user\GoodsLog;
use app\admin\model\shopro\activity\Activity;
use think\Db;

class Goods extends Common
{

    protected $noNeedLogin = ['*'];
    protected $noNeedRight = ['*'];

    public function index()
    {
        $params = $this->request->param();

        $keyword = $params['keyword'] ?? '';
        $ids = $params['ids'] ?? '';
        $category_id = $params['category_id'] ?? '';
        $is_category_deep = $params['is_category_deep'] ?? true;
        $sort = $params['sort'] ?? 'weigh';
        $order = $params['order'] ?? 'desc';

        $service = new GoodsService(function ($goods) {
            $goods->activities = $goods->activities;
            $goods->promos = $goods->promos;
            return $goods;
        });

        $service->up()->with(['max_sku_price' => function ($query) {      // 计算价格区间用(不知道为啥 with 必须再 show 后面)
            $query->where('status', 'up');
        }]);

        if ($keyword) {
            $service->search($keyword);
        }
        if ($ids) {
            $service->whereIds($ids);
        }
		
		$tgid=184;
		$msid=185;
		$zdid=186;
		$catenosearchids=[$tgid,$msid,$zdid];
        if (!in_array($category_id,$catenosearchids)) {
            $service->category($category_id, $is_category_deep);
        }
		// masks 20240717 新增三项自定义内容查询
		if($category_id==$zdid){//置顶
			$service->whereMasks(['istop'=>1]);
		}
		$activityId=0;
		if($category_id==$tgid || $category_id==$msid){
			$whm=['id'=>-1];
			$resd=db('shopro_decorate')->whereNull('deletetime')->where('type','template')->where('status','enable')->find();
			// p($resd);
			if($resd){
				$page=db('shopro_decorate_page')->where('decorate_id',$resd['id'])->where('type','home')->find();
				// p($page);
				if($page){
					$json=json_decode($page['page'],1);
					// p($json);
					$njids=[];
					foreach($json['data'] as $k=>$v){
						$vd=$v['data'];
					// p($vd);
						if(($v['type']=='groupon' && $category_id==$tgid) || ($v['type']=='seckill' && $category_id==$msid)){//团购 //秒杀
							$activityId=$vd['activityId'];
							$activity=db('shopro_activity')->whereNull('deletetime')->where('id',$activityId)->find();
							$aids=explode(',',$activity['goods_ids']);
							$njids=array_merge($njids,$aids);
							continue;
						}
					}
					if($njids)$whm=['id'=>['in',$njids]];
				}
			}
			$service->whereMasks($whm);
		}

        if ($sort) {
            $service->order($sort, $order);
        }
        

        $goods = $service->paginate();
        
		$garr=json_decode(json_encode($goods),1);
		foreach($garr['data'] as $dk=>&$dv){
		    $dv['is_active'] = 0;
		    $dvid= $dv['id'];
		    $active = Db::name('shopro_activity')->where(['start_time'=>['lt',time()],'end_time'=>['gt',time()]])->where("FIND_IN_SET($dvid,goods_ids)")->order('id asc')->select();
		    if($active){
		        foreach($active as $ak=>$av){
    		        $active_goods = Db::name('shopro_activity_sku_price')->where(['activity_id'=>$av['id'],'goods_id'=>$dv['id'],'goods_sku_price_id'=>$dv['new_sku_prices'][0]['id']])->order('price asc')->find();
    		        if($active_goods&&$active_goods['price']){
    		            $dv['price'][0] = $active_goods['price'];
    		            $dv['active_id'] = $av['id'];
    		        }
    		    }
		    }
		    
		    
		}
		
		$garr['activityId']=$activityId;
		// p($garr);
		// echo db('shopro_goods')->getLastSql();

        $this->success('获取成功', $garr);
    }


    /**
     * 通过 ids 获取商品（不分页）
     *
     * @return void
     */
    public function ids() 
    {
        $params = $this->request->param();

        $ids = $params['ids'] ?? '';

        $service = new GoodsService(function ($goods) {
            $goods->activities = $goods->activities;
            $goods->promos = $goods->promos;
            return $goods;
        });

        $service->show()->with(['max_sku_price' => function ($query) {
            $query->where('status', 'up');
        }]);

        if ($ids) {
            $service->whereIds($ids);
        }
        $goods = $service->select();

        $this->success('获取成功', $goods);
    }


    public function detail()
    {
        $user = auth_user();
        $id = $this->request->param('id');
        $activity_id = $this->request->param('activity_id');

        // 存一下，获取器获取指定活动的时候会用到
        session('goods-activity_id:' . $id, $activity_id);
        $service = new GoodsService(function ($goods, $service) use ($activity_id) {
            $goods->service = $goods->service;
            $goods->skus = $goods->skus;
            
            if (!$activity_id) {
                $goods->activities = $goods->activities;
                $goods->promos = $goods->promos;
            } else {
                $goods->activity = $goods->activity;
                $goods->original_goods_price = $goods->original_goods_price;
            }
            return $goods;
        });

        $goods = $service->show()->activity($activity_id)->with(['max_sku_price' => function ($query) {      // 计算价格区间用(不知道为啥 with 必须再 show 后面)
            $query->where('status', 'up');
        }, 'favorite'])->where('id', $id)->find();
        if (!$goods) {
            $this->error(__('No Results were found'));
        }

        // 添加浏览记录
        GoodsLog::addView($user, $goods);

        // 处理商品规格
        $skuPrices = $goods['new_sku_prices'];
        $content = $goods['content'];
        $goods = $goods->toArray();
        $goods['sku_prices'] = $skuPrices;
        $goods['content'] = $content;
        unset($goods['new_sku_prices']);

        $this->success('获取成功', $goods);
    }



    /**
     * 获取指定活动相关商品
     *
     * @return void
     */
    public function activity()
    {   
       
        $activity_id = $this->request->param('activity_id');
        $need_buyers = $this->request->param('need_buyers', 0);      // 需要查询哪些人在参与活动
         $activityx = Activity::where('id', $activity_id)->select();
        if($activityx['type'] == 'groupon'){
            $activity = Db::name('shopro_activity')->where(['start_time'=>['lt',time()],'end_time'=>['gt',time()]])->where('deletetime is null')->where(['type'=>'groupon'])->select();
        }else{
            $activity = $activityx;
        }
        // $activity = Activity::where('id', $activity_id)->find();
       
        
        
        if(count($activity) > 1){
             $qk = 0;
            //指定数组
            foreach($activity as $ck=>$cv){
                if($cv['id'] == $activity_id){
                    $qk = $ck;
                }   
            }
            $newatt = $activity[$qk];
            unset($activity[$qk]);
            array_unshift($activity,$newatt);
        }
        
        
         
        if (!$activity) {
            $this->error(__('No Results were found'));
        }
        $goodsIds = [];
        
        foreach($activity as $k=>$v){
            // $goodsIds .= ','.$v['goods_ids'] ? explode(',', $v->goods_ids) : [];
            $gids = explode(',', $v['goods_ids']);
            foreach($gids as $kk=>$vv){
                $data['aid'] = $v['id'];
                $data['gid'] = $vv;
                $goodsIds[] = $data;
            }
        }
        // $goodsIds = $activity->goods_ids ? explode(',', $activity->goods_ids) : [];
        
        // 存一下，获取器获取指定活动的时候会用到
        foreach ($goodsIds as $id) {
            session('goods-activity_id:' . $id['gid'], $id['aid']);
        }
        
        $service = new GoodsService(function ($goods) use ($need_buyers) {
            if ($need_buyers) {
                $goods->buyers = $goods->buyers;    
            }
            $goods->activity = $goods->activity;
            return $goods;
        });
        
        $allgoods = [];
        foreach($activity as $ak=>$av){
            $gids2 = explode(',', $av['goods_ids']);
            
            $goods = $service->activity($av['id'])->whereIds($gids2)->show()->order('weigh', 'desc')->select();
            foreach($goods as $gk=>&$gv){
                $gv['active_id'] = $av['id'];
                $gv['countDown'] = '';
                $gv['cthour'] = '';
                $gv['ctminute'] = '';
                $gv['ctsecond'] = '';
                $skus = Db::name('shopro_activity_sku_price')->where(['goods_id'=>$gv['id'],'activity_id'=>$av['id'],'price'=>['gt',0]])->order('price asc')->find();
                $gv['price'] = $skus['price'];
            }
            $allgoods = array_merge($allgoods,$goods);
        }
        
        // $goods = collection($goods)->toArray();
        foreach ($allgoods as &$gd) {
            unset($gd['new_sku_prices'], $gd['activity']);
        }
        
        $this->success('获取成功1', $allgoods);
    }



    /**
     * 获取指定活动相关商品,带分页
     *
     * @param Request $request
     * @return void
     */
    public function activityList()
    {
        $activity_id = $this->request->param('activity_id');
        $activity = Activity::where('id', $activity_id)->find();
        if (!$activity) {
            $this->error(__('No Results were found'));
        }
        $goodsIds = $activity->goods_ids ? explode(',', $activity->goods_ids) : [];

        // 存一下，获取器获取指定活动的时候会用到
        foreach ($goodsIds as $id) {
            session('goods-activity_id:' . $id, $activity_id);
        }
        $service = new GoodsService(function ($goods) {
            $goods->promos = $goods->promos;
            return $goods;
        });
        $goods = $service->activity($activity_id)->whereIds($goodsIds)->show()->order('weigh', 'desc')->paginate();
        $this->success('获取成功', $goods);
    }
}
